<template>
  <div class="callback-container">
    <div class="callback-card">
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <h3>正在处理登录信息...</h3>
        <p>请稍候</p>
      </div>

      <div v-else-if="success" class="success-state">
        <div class="success-icon">✓</div>
        <h3>登录成功！</h3>
        <p>欢迎回来，{{ userInfo.nickname }}</p>
        <div class="redirect-info">
          <p>正在跳转到首页...</p>
        </div>
      </div>

      <div v-else class="error-state">
        <div class="error-icon">✕</div>
        <h3>登录失败</h3>
        <p class="error-message">{{ errorMessage }}</p>
        <button @click="retryLogin" class="retry-button">重新登录</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoginCallback',
  data() {
    return {
      loading: true,
      success: false,
      errorMessage: '',
      userInfo: {
        nickname: ''
      }
    }
  },
  mounted() {
    console.log('[LoginCallback] 组件已挂载，开始处理回调')
    this.handleCallback()
  },
  methods: {
    /**
     * 处理登录回调
     */
    async handleCallback() {
      try {
        console.log('[LoginCallback] ========== 开始处理回调 ==========')
        console.log('[LoginCallback] 当前完整URL:', window.location.href)
        console.log('[LoginCallback] hash:', window.location.hash)
        console.log('[LoginCallback] search:', window.location.search)
        console.log('[LoginCallback] pathname:', window.location.pathname)
        
        // 从URL参数中获取登录信息（注意：Vue Router使用hash路由，参数在hash中）
        let urlParams = new URLSearchParams(window.location.search)
        
        // 如果search为空，尝试从hash中解析
        if (window.location.hash) {
          const hash = window.location.hash
          const hashPath = hash.split('?')[1] // 获取?后面的部分
          if (hashPath) {
            urlParams = new URLSearchParams(hashPath)
          }
        }
        
        const success = urlParams.get('success')
        const token = urlParams.get('token')
        const refreshToken = urlParams.get('refresh_token')
        const expiresIn = urlParams.get('expires_in')
        const userInfoStr = urlParams.get('user_info')

        console.log('[LoginCallback] 解析后的参数:', {
          success,
          token: token ? token.substring(0, 20) + '...' : null,
          userInfoStr: userInfoStr ? userInfoStr.substring(0, 50) + '...' : null
        })

        if (success === 'true' && token) {
          // 解析用户信息
          let userInfo = {}
          if (userInfoStr) {
            try {
              // 首先尝试URL解码再JSON解析
              userInfo = JSON.parse(decodeURIComponent(userInfoStr))
              console.log('[LoginCallback] 用户信息解析成功（经过URL解码）')
            } catch (e) {
              console.warn('[LoginCallback] URL解码失败，尝试直接解析:', e)
              try {
                // 如果URL解码失败，尝试直接解析
                userInfo = JSON.parse(userInfoStr)
                console.log('[LoginCallback] 用户信息解析成功（直接解析）')
              } catch (e2) {
                console.error('[LoginCallback] 解析用户信息失败:', e2)
                userInfo = { nickname: '用户' }
              }
            }
          }

          // 保存token到localStorage（注意key要改为'token'而不是'access_token'）
          localStorage.setItem('token', token)
          if (refreshToken) {
            localStorage.setItem('refresh_token', refreshToken)
          }
          if (expiresIn) {
            const expiresAt = Date.now() + parseInt(expiresIn) * 1000
            localStorage.setItem('token_expires_at', expiresAt.toString())
          }

          // 保存用户信息
          localStorage.setItem('user_info', JSON.stringify(userInfo))
          this.userInfo = userInfo

          // 调用Pinia store的login方法更新状态
          const { useUserStore } = await import('@/stores/user')
          const userStore = useUserStore()
          userStore.login(token, userInfo)

          // 标记登录成功
          this.success = true
          this.loading = false

          // 根据是否管理员跳转
          try {
            const { userAPI } = await import('@/api/novel')
            const check = await userAPI.isAdmin()
            const isAdmin = check?.data?.is_admin
            this.$router.replace(isAdmin ? '/admin' : '/author')
          } catch (e) {
            this.$router.replace('/author')
          }

          console.log('[LoginCallback] 登录成功！用户信息:', userInfo)
          console.log('[LoginCallback] 已保存token到localStorage并更新Pinia状态')

          // 1秒后跳转到首页
          setTimeout(() => {
            this.$router.push('/')
          }, 1000)

        } else {
          // 登录失败
          this.success = false
          this.loading = false
          this.errorMessage = urlParams.get('message') || '登录失败，请重试'
          console.error('登录失败:', this.errorMessage)
        }

      } catch (error) {
        console.error('[LoginCallback] 处理回调失败:', error)
        console.error('[LoginCallback] 错误详情:', error.stack)
        this.loading = false
        this.success = false
        this.errorMessage = '处理登录信息时出错：' + error.message
      }
    },

    /**
     * 重新登录
     */
    retryLogin() {
      this.$router.push('/dingtalk-login')
    }
  }
}
</script>

<style scoped>
.callback-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.callback-card {
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 450px;
  width: 100%;
  text-align: center;
}

.loading-state,
.success-state,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.success-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  animation: scaleIn 0.5s ease-out;
}

.error-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  font-size: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  animation: scaleIn 0.5s ease-out;
}

@keyframes scaleIn {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 600;
}

p {
  color: #666;
  font-size: 16px;
  margin: 10px 0;
}

.error-message {
  color: #f5576c;
  font-size: 14px;
  margin: 15px 0;
}

.redirect-info {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9ff;
  border-radius: 8px;
}

.redirect-info p {
  color: #667eea;
  font-size: 14px;
  margin: 0;
}

.retry-button {
  margin-top: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.retry-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}
</style>

